
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Linq.Extensions;
using Abp.Extensions;
using Abp.Domain.Repositories;

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using WebApp.Navigations;
using WebApp.Navigations.Dtos;
using WebApp.Navigations.DomainService;
using WebApp.Authorization;
using WebApp.Helper;
using Abp.UI;

namespace WebApp.Navigations
{
    /// <summary>
    /// 应用层服务的接口实现方法
    ///</summary>
    [AbpAuthorize]
    public class UiMenuAppService : WebAppAppServiceBase, IUiMenuAppService
    {
         private readonly IRepository<UiMenu, Guid>        _uiMenuRepository;



        private readonly IUiMenuManager _uiMenuManager;
        /// <summary>
        /// 构造函数
        ///</summary>
        public UiMenuAppService(
		IRepository<UiMenu, Guid>  uiMenuRepository
              ,IUiMenuManager uiMenuManager       

             )
            {
            _uiMenuRepository = uiMenuRepository;
             _uiMenuManager=uiMenuManager;


            }


            /// <summary>
                /// 获取的分页列表信息
                ///      </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            [AbpAuthorize(UiMenuPermissions.Query)]
            public async Task<PagedResultDto<UiMenuListDto>> GetPaged(GetUiMenusInput input)
		{

		    var query = _uiMenuRepository.GetAll()
                           
                            //模糊搜索Name
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Name.Contains(input.FilterText))                                                                                      
                            //模糊搜索DisplayName
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.DisplayName.Contains(input.FilterText))                                                                                      
                            //模糊搜索PermissionKey
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.PermissionKey.Contains(input.FilterText))                                                                                      
                            //模糊搜索Path
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Path.Contains(input.FilterText))                                                                                      
                            //模糊搜索Remark
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Remark.Contains(input.FilterText))                                                                                      
                            //模糊搜索Icon
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Icon.Contains(input.FilterText))                                                           
			;
			// TODO:根据传入的参数添加过滤条件

			var count = await query.CountAsync();

			var uiMenuList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

		  var uiMenuListDtos = ObjectMapper.Map<List<UiMenuListDto>>(uiMenuList);

			return new PagedResultDto<UiMenuListDto>(count,uiMenuListDtos);
		}

		/// <summary>
		/// 获取的分页列表信息
		///      </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(UiMenuPermissions.Query)]
		public async Task<List<UiMenuTreeDto>> GetPagedTree(GetUiMenusInput input)
		{

			var query = _uiMenuRepository.GetAll()

						  //模糊搜索Name
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Name.Contains(input.FilterText))
						  //模糊搜索DisplayName
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.DisplayName.Contains(input.FilterText))
						  //模糊搜索PermissionKey
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.PermissionKey.Contains(input.FilterText))
						  //模糊搜索Path
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Path.Contains(input.FilterText))
						  //模糊搜索Remark
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Remark.Contains(input.FilterText))
						  //模糊搜索Icon
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Icon.Contains(input.FilterText))
			;
			// TODO:根据传入的参数添加过滤条件

			var count = await query.CountAsync();

			var uiMenuList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.Select(u=>ObjectMapper.Map<UiMenuTreeDto>(u)).ToListAsync();
			List<UiMenuTreeDto> uiTree = new List<UiMenuTreeDto>();
			UiMenuTreeDto rootRoot = new UiMenuTreeDto
			{
				Id = Guid.Empty,
				Pid = Guid.Empty,
				DisplayName = "根节点",
				children = new List<UiMenuTreeDto>()
				
			};

			RecursionTreeHelper.LoopChildrenUiMenuTree(uiMenuList, rootRoot);

			List<UiMenuTreeDto> tT = rootRoot.children;



			return tT;
		}



		/// <summary>
		/// 通过指定id获取UiMenuListDto信息
		/// </summary>
		//[AbpAuthorize(UiMenuPermissions.Query)]
		public async Task<UiMenuListDto> GetById(EntityDto<Guid> input)
		{
			var entity = await _uiMenuRepository.GetAsync(input.Id);

			var dto = ObjectMapper.Map<UiMenuListDto>(entity);
			return dto;
 		}

		/// <summary>
		/// 获取编辑 
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(UiMenuPermissions.Create,UiMenuPermissions.Edit)]
		public async Task<GetUiMenuForEditOutput> GetForEdit(NullableIdDto<Guid> input)
		{
			var output = new GetUiMenuForEditOutput();
UiMenuEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _uiMenuRepository.GetAsync(input.Id.Value);
				editDto = ObjectMapper.Map<UiMenuEditDto>(entity);
			}
			else
			{
				editDto = new UiMenuEditDto();
			}
    


            output.UiMenu = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(UiMenuPermissions.Create,UiMenuPermissions.Edit)]
		public async Task CreateOrUpdate(CreateOrUpdateUiMenuInput input)
		{

			if (input.UiMenu.Id.HasValue)
			{
				await Update(input.UiMenu);
			}
			else
			{
				await Create(input.UiMenu);
			}
		}


		/// <summary>
		/// 新增
		/// </summary>
		[AbpAuthorize(UiMenuPermissions.Create)]
		public async Task<UiMenuEditDto> Create(UiMenuEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<UiMenu>(input);

			var ui = await _uiMenuManager.QueryUiMenusAsNoTracking().FirstOrDefaultAsync(u => u.Name == input.Name);
			if (ui != null)
			{
				throw new UserFriendlyException(string.Format("模块名{0}已被占用.", input.Name));
			}
			//调用领域服务
			entity = await _uiMenuManager.CreateAsync(entity);

            var dto=ObjectMapper.Map<UiMenuEditDto>(entity);
            return dto;
		}

		/// <summary>
		/// 编辑
		/// </summary>
		[AbpAuthorize(UiMenuPermissions.Edit)]
		public async Task Update(UiMenuEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

		 var entity = await _uiMenuRepository.GetAsync(input.Id.Value);
          //  input.MapTo(entity);
          //将input属性的值赋值到entity中
             ObjectMapper.Map(input, entity);
            await _uiMenuManager.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除信息
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(UiMenuPermissions.Delete)]
		public async Task Delete(EntityDto<Guid> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
            await _uiMenuManager.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除UiMenu的方法
		/// </summary>
		[AbpAuthorize(UiMenuPermissions.BatchDelete)]
		public async Task BatchDelete(List<Guid> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
            await _uiMenuManager.BatchDelete(input);
		}




		//// custom codes
		public async Task<PermissionTreeDto> GetPermissionTree(Guid? pid = null, bool IsUserId = false, bool needbtn = false)
		{

			var allMenu = await _uiMenuManager.QueryUiMenusAsNoTracking().OrderBy(u => u.Order).Select(u => new PermissionTreeDto
			{
				value = u.Id,
				label = u.DisplayName,
				Pid = u.Pid,
				order = u.Order,
				title = u.DisplayName,
				expand = true,
				permissionKey= u.PermissionKey
			})
			.ToListAsync();
			foreach(var item in allMenu)
			{
				item.label = L(item.label);
				item.title = item.label;

			}

			PermissionTreeDto rootRoot = new PermissionTreeDto
			{
				value = Guid.Empty,
				Pid = null,
				label = "根节点"
			};

			RecursionTreeHelper.LoopToAppendChildren(allMenu, rootRoot, pid, needbtn);

			return rootRoot;
		}


		//// custom codes end

	}
}


